import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/singlechildbutton.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/singlemessage.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/dio/UserDio.dart';
import 'package:wayofdressing/good_method/decode_base64_to_bytes.dart';
import 'package:wayofdressing/screens/chat_screen.dart';
import 'package:wayofdressing/all_information/message_datas.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/dio/MessageDio.dart';

class MessagesScreen extends StatelessWidget {
  static final String id = 'messagesscreen';
  TextEditingController textEditingController = TextEditingController();

  void _fetchLatestMessages() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int userId = prefs.getInt('id')!;
    try {
      Response<dynamic> response = await getLatestMessagesBySenderId(
        userId: userId,
        dio: dio,
      );
      dynamic data = response.data['data'];
      latestMessages.clear();
      for (dynamic item in data) {
        String latestMessage = item['messageText'];
        int receiverId = item['receiver']['id'];
        String sentAt= item['sentAt'];
        Map<String, dynamic> message;
        if(receiverId!=userId){
          String receiverName = item['receiver']['name'];
          String? base64Image = item['receiver']['userDetailDTO']['imageBytes'];
          dynamic headImage=AssetImage('images/peanut.jpg');
          if (base64Image != null && base64Image.isNotEmpty) {
            Uint8List imageBytes = decodeBase64ToBytes(base64Image);
            headImage=MemoryImage(imageBytes);
          }
          message = {
            'sentAt':sentAt,
            'latestMessage': latestMessage,
            'receiverId': receiverId,
            'receiverName': receiverName,
            'headImage':headImage,
          };
        }
        else{
          String receiverName = item['sender']['name'];
          String? base64Image = item['sender']['userDetailDTO']['imageBytes'];
          dynamic headImage=AssetImage('images/peanut.jpg');
          if (base64Image != null && base64Image.isNotEmpty) {
            Uint8List imageBytes = decodeBase64ToBytes(base64Image);
            headImage=MemoryImage(imageBytes);
          }
          message = {
            'sentAt':sentAt,
            'latestMessage': latestMessage,
            'receiverId': receiverId,
            'receiverName': receiverName,
            'headImage':headImage,
          };
        }
        latestMessages.add(message);
      }
      latestMessages.sort((a,b)=>a['sentAt'].compareTo(b['sentAt']));
    } catch (e) {
      // 处理异常情况，例如显示错误消息或者重新尝试获取数据
      print('Error fetching latest messages: $e');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfffffaf0),
        appBar: AppBar(
          backgroundColor: Color(0xfffffaf0),
          elevation: 0,
          toolbarHeight: 80,
          leadingWidth: 200,
          leading: Row(
            children: [
              SizedBox(
                width: 10,
              ),
              MenuAnchor(
                menuChildren: [
                  InMenuButton(
                    text: '发送信息',
                    onPressed: () {
                      showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                              side: BorderSide(color: Colors.indigo, width: 3),
                            ),
                            backgroundColor: Colors.white,
                            title: Text(
                              '发送消息',
                              style: TextStyle(color: Colors.black),
                            ),
                            content: TextField(
                              controller: textEditingController,
                              decoration: InputDecoration(
                                label: Text('请输入对方id'),
                                labelStyle: TextStyle(
                                    color: Colors.teal.withOpacity(0.65),
                                    fontSize: 12),
                                enabledBorder: UnderlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Colors.grey), // 默认状态颜色
                                ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Colors.grey), // 聚焦状态颜色
                                ),
                              ),
                            ),
                            actions: <Widget>[
                              TextButton(
                                child: Text('确定',
                                    style: TextStyle(color: Colors.black)),
                                onPressed: () async {
                                  Response response = await getUserById(
                                      int.parse(textEditingController.text),
                                      dio);
                                  dynamic data = response.data['data'];
                                  String? base64Image =
                                      data['userDetailDTO']['imageBytes'];
                                  if (base64Image != null &&
                                      base64Image.isNotEmpty) {
                                    Uint8List imageBytes =
                                        decodeBase64ToBytes(base64Image);
                                    ImageProvider receiverImage =
                                        MemoryImage(imageBytes);
                                    Navigator.pushNamed(
                                      context,
                                      ChatScreen.id,
                                      arguments: {
                                        'receiverId': int.parse(
                                            textEditingController.text),
                                        'headImage': receiverImage,
                                        'receiverName': data['name']
                                      },
                                    ).then((_) {
                                      _fetchLatestMessages();
                                      Navigator.of(context).pop();
                                    });
                                  }
                                },
                              ),
                            ],
                          );
                        },
                      );
                    },
                  ),
                  InMenuButton(
                    text: '添加好友',
                    onPressed: () {},
                  ),
                  InMenuButton(
                    text: '创建群',
                    onPressed: () {},
                  ),
                  InMenuButton(
                    text: '添加群',
                    onPressed: () {},
                  ),
                  InMenuButton(
                    text: '扫一扫',
                    onPressed: () {},
                  ),
                  InMenuButton(
                    text: '我的二维码',
                    onPressed: () {},
                  ),
                ],
                style: MenuStyle(
                  alignment: Alignment(-0.7, 1),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25),
                    ),
                  ),
                  padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
                  shadowColor: MaterialStateProperty.all(Colors.transparent),
                  backgroundColor: MaterialStateProperty.all(
                    Colors.black.withOpacity(0.4),
                  ),
                ),
                builder: (BuildContext context, MenuController controller,
                    Widget? child) {
                  return GestureDetector(
                    onTap: () {
                      if (controller.isOpen) {
                        controller.close();
                      } else {
                        controller.open();
                      }
                    },
                    child: Icon(
                      Icons.add_rounded,
                      size: kAppBarButtonSize,
                      color: Colors.black,
                    ),
                  );
                },
              ),
            ],
          ),
          actions: [
            MenuAnchor(
              menuChildren: [
                InMenuButton(
                  onPressed: () {},
                  text: '待开发',
                  alignment: Alignment.centerRight,
                ),
              ],
              style: MenuStyle(
                shape: MaterialStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                  ),
                ),
                alignment: Alignment(-3, 0.5),
                padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
                shadowColor: MaterialStateProperty.all(Colors.transparent),
                backgroundColor: MaterialStateProperty.all(
                  Colors.black.withOpacity(0.4),
                ),
              ),
              builder: (BuildContext context, MenuController controller,
                  Widget? child) {
                return GestureDetector(
                  onTap: () {
                    if (controller.isOpen) {
                      controller.close();
                    } else {
                      controller.open();
                    }
                  },
                  child: Icon(
                    Icons.keyboard_control_rounded,
                    size: kAppBarButtonSize,
                    color: Colors.black,
                  ),
                );
              },
            ),
            SizedBox(
              width: 20,
            )
          ],
        ),
        body: Row(
          children: [
            SizedBox(
              width: 20,
            ),
            Expanded(
              child: Column(
                children: [
                  Expanded(
                    flex: 4,
                    child: Row(
                      children: [
                        singleChildButton(
                          onPressed: () {},
                          childWidget: Text(
                            '我的圈子',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 24,
                            ),
                          ),
                          flexNumber: 4,
                          marginNumber: 4.0,
                        ),
                        singleChildButton(
                          onPressed: () {},
                          flexNumber: 3,
                          marginNumber: 4.0,
                          childWidget: Text(
                            '朋友',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 24,
                            ),
                          ),
                        ),
                        singleChildButton(
                          onPressed: () {},
                          flexNumber: 3,
                          marginNumber: 4.0,
                          childWidget: Text(
                            '通知',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 24,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Expanded(
                    flex: 20,
                    child: ListView.builder(
                      itemCount: latestMessages.length,
                      itemBuilder: (context, index) {
                        return singleMessage(
                            name: latestMessages[index]['receiverName'],
                            text: latestMessages[index]['latestMessage'],
                            headImage: latestMessages[index]['headImage'],
                            onPressed: () {
                              Navigator.pushNamed(context, ChatScreen.id,
                                  arguments: {
                                    'receiverId': latestMessages[index]
                                        ['receiverId'],
                                    'headImage': latestMessages[index]
                                        ['headImage'],
                                    'receiverName': latestMessages[index]
                                        ['receiverName']
                                  });
                            });
                      },
                      // children: [
                      //   singleMessage(
                      //     onPressed: (){
                      //       Navigator.pushNamed(context, ChatScreen.id,arguments: {'receiverId':3});
                      //     },
                      //     text: '检测到违规行为，您将遭到封号处理！',
                      //     name: '官方',
                      //     headImage: AssetImage('images/peanut.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){
                      //     },
                      //     text: '1974年,第一次在东南亚打自由搏击',
                      //     name: '程天然',
                      //     headImage: AssetImage('images/ctr.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '老师们大家好，我是练习时长两年半的...',
                      //     name: '胡月冰',
                      //     headImage: AssetImage('images/hyb.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '我才是真正的社区gangster,you know m3!',
                      //     name: '梁嘉伦',
                      //     headImage: AssetImage('images/ljl.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '我不给你补呀铁铁，蛋也不给你补!',
                      //     name: '刘子璇',
                      //     headImage: AssetImage('images/lzx.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '劝你速度把鞋子链接发我',
                      //     name: '舒程锦',
                      //     headImage: AssetImage('images/scj.jpg'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '亚比，囧囧囧~喵喵喵~',
                      //     name: '邓超out',
                      //     headImage: AssetImage('images/dc.png'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '大老爷们用化妆品，比**娘们还娘！',
                      //     name: '老师',
                      //     headImage: AssetImage('images/laoshi.png'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '我就败在这个家伙身上，当兵吧你！',
                      //     name: '败者',
                      //     headImage: AssetImage('images/wojiu.png'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '对得起我们吗？***，退钱！',
                      //     name: '退钱哥',
                      //     headImage: AssetImage('images/tuiqian.png'),
                      //   ),
                      //   singleMessage(
                      //     onPressed: (){},
                      //     text: '*的，最烦装13的人！',
                      //     name: '那英',
                      //     headImage: AssetImage('images/naying.png'),
                      //   ),
                      // ],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              width: 20,
            ),
          ],
        ));
  }
}
